package kurtis.rx.androidexamples;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

import java.util.concurrent.Callable;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observable;
import rx.Single;
import rx.SingleSubscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2016/3/25.
 */
public class MySingleObservableTest extends AppCompatActivity {

    @Bind(R.id.clock)
    TextView clock;
    //  时钟
    private int count = 1;
    private Subscription subscription;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mysingletest);
        ButterKnife.bind(this);
        createObservable();
    }

    private void createObservable() {
        Observable.just("Hello, world!")
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        System.out.println(s);
                    }
                });
    }

/*    *//**
     * 用Sigln做异步处理
     *//*
    private void createObservable() {

        Single<Integer> observable = Single.fromCallable(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
//              果然是在子线程
                Thread.sleep(5000);
                count++;
                return count;
            }
        });

//      添加订阅者
        subscription = observable
//                     可以理解为被观察者的方法在子线程中进行
                .subscribeOn(Schedulers.io())
//                      观察者的方法在主线程中
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleSubscriber<Integer>() {
                    @Override
                    public void onSuccess(Integer value) {
                        clock.setText(String.valueOf(value));

                    }

                    @Override
                    public void onError(Throwable error) {

                    }
                });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (subscription!=null&&subscription.isUnsubscribed()){
//          防止内存泄漏，释放订阅的对象
            subscription.unsubscribe();
        }

    }*/
}
